package com;


import com.alibaba.fastjson.JSON;
import org.smartboot.http.HttpRequest;
import org.smartboot.http.HttpResponse;
import org.smartboot.http.enums.HttpStatus;
import org.smartboot.http.server.handle.HttpHandle;
import org.smartboot.http.utils.AntPathMatcher;

import javax.print.DocFlavor;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

public class HttpNginxRouteHandle extends HttpHandle {

    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    private Map<String, String> handleUrlMap = new LinkedHashMap<>();
    /**
     * 默认404
     */
    private HttpHandle defaultHandle = new HttpHandle() {
        @Override
        public void doHandle(HttpRequest request, HttpResponse response) throws IOException {
            response.setHttpStatus(HttpStatus.NOT_FOUND);
        }
    };

    @Override
    public void doHandle(HttpRequest request, HttpResponse response) throws IOException {
        String uri = request.getRequestURI();
        HttpHandle httpHandle = defaultHandle;// 404 not found
        for (Map.Entry<String, String> entity : handleUrlMap.entrySet()) {
            if (PATH_MATCHER.match(entity.getKey(), uri)) {
                String uriPath = PATH_MATCHER.extractPathWithinPattern(entity.getKey(), uri);
                httpHandle = new HttpServiceHandle(entity.getValue() + uriPath);
                break;
            }
        }

        httpHandle.doHandle(request, response);
    }

    /**
     * 配置URL路由
     *
     * @param localUrlPattern url匹配
     * @param targetUrl       处理handle
     * @return
     */

    public HttpNginxRouteHandle route(String localUrlPattern, String targetUrl) {
        handleUrlMap.put(localUrlPattern, targetUrl);
        return this;
    }


    public static void main(String[] args) {
        System.out.println("args = " + PATH_MATCHER.extractPathWithinPattern("/**", "/a/b/guojian"));

        Map<String, String> a = PATH_MATCHER.extractUriTemplateVariables("/**", "/a/b/aa.txt");

        System.out.println("JSON.toJSONString(a) = " + JSON.toJSONString(a));
    }


}
